//
//  DeleteDataViewController.m
//  Daybook
//
//  Created by dllo on 16/6/4.
//  Copyright © 2016年 zhangbin. All rights reserved.
//

#import "DeleteDataViewController.h"
#import "Common.h"
#import "MHActionSheet.h"


@interface DeleteDataViewController ()
<
UITableViewDataSource,
UITableViewDelegate,
DeleteDatePickerViewDelegate,
UIAlertViewDelegate
>

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong) NSArray *nameArr;
@property (nonatomic, strong) UIView *headLine;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) NSMutableArray *selectSource;

// sheet数据
@property (nonatomic, strong) NSMutableArray *accountBookArr;
@property (nonatomic, strong) NSMutableArray *classArr;

@property (nonatomic, strong) DeleteDatePickerView *datePickerView;

@property (nonatomic, strong) DeleteDataModel *model;

@property (nonatomic, strong) UIButton *finishButton;

@property (nonatomic, strong) NSDate *beginDate;
@property (nonatomic, strong) NSDate *endDate;
@property (nonatomic, strong) UIAlertView *alert;

@property (nonatomic, strong) UIAlertController *alertView;

@end

@implementation DeleteDataViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [self createData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    
}

- (void)createData {
    self.accountBookArr = [NSMutableArray array];
    self.classArr = [NSMutableArray array];
    self.model = [DeleteDataModel new];

    
    NSMutableArray *indexArr = [NSMutableArray array];
    RLMRealm *realm = [RLMRealm defaultRealm];
    RLMResults *results = [DayBook allObjects];
    for (DayBook *dayBook in results) {
        [indexArr addObject:dayBook.accountBookIndex];
    }
    for (NSString *indexStr in indexArr) {
        NSArray *tempArr = [[AccountBookSQL shareDataBaseTool] select];
        AccountBookModel *model = [AccountBookModel new];
        model = tempArr[indexStr.integerValue];
        [_accountBookArr addObject: model.accountBookName];
    }
    
    
    NSMutableSet *classSet = [NSMutableSet set];
    
    for (NSInteger i = 0; i < indexArr.count; i++) {
        NSString *tempStr = indexArr[0];
        RLMResults *classResults = [DayBook objectsInRealm:realm where:@"accountBookIndex = %@", tempStr];
        for (DayBook *tempAccout in classResults) {
            for (Account *temp in tempAccout.bookContent) {
                [classSet addObject:temp.name];
            }
        }
    }
    for (NSString *tempStr in classSet) {
        [_classArr addObject:tempStr];
    }
    
    if (_classArr.count == 0) {
        [_classArr addObject:@"没有分类数据"];
    }
    if (_accountBookArr.count == 0) {
        [_accountBookArr addObject:@"没有账本数据"];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.beginDate = [[CalendarTool shareCalendarTool] firstDayFromDate:[NSDate date]];
    self.endDate = [[CalendarTool shareCalendarTool] lastDayFromDate:[NSDate date]];
    [self createView];
    [self createDatePickerView];
}

- (void)createDatePickerView {
    self.datePickerView = [[DeleteDatePickerView alloc] initWithFrame:CGRectMake(0, MAIN_HEIGHT - 350, MAIN_WIDTH, 350)];
    _datePickerView.delegate = self;
    [self.view addSubview:_datePickerView];
    [self.datePickerView hide];
}

- (void)createView {
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backButton setImage:[UIImage imageNamed:@"cha.png"] forState:UIControlStateNormal];
    _backButton.frame = CGRectMake([CalculateFrameView setWidth:15], [CalculateFrameView setHeight:30], [CalculateFrameView setWidth:25], [CalculateFrameView setHeight:25]);
    [self.view addSubview:_backButton];
    [_backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    _titleLabel.center = CGPointMake(MAIN_WIDTH / 2, 41);
    _titleLabel.text = @"批量删除";
    _titleLabel.font = [UIFont systemFontOfSize:18];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_titleLabel];
    
    self.finishButton = ({
        BaseButton *tempButton = [BaseButton buttonWithType:UIButtonTypeCustom];
        tempButton.frame = CGRectMake(365 / 414.0 * MAIN_WIDTH, [CalculateFrameView setHeight:28], 30 / 414.0 * MAIN_WIDTH, 30 / 414.0 * MAIN_WIDTH);
        [self.view addSubview:tempButton];
        [tempButton setImage:[UIImage imageNamed:@"duihao.png"] forState:UIControlStateNormal];
        [tempButton addTarget:self action:@selector(finishButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        tempButton;
    });
    
    self.headLine = [[UIView alloc] initWithFrame:CGRectMake(0, 63, MAIN_WIDTH, 1)];
    [self.view addSubview:_headLine];
    _headLine.backgroundColor = LINE_COLOR;
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, MAIN_WIDTH, MAIN_HEIGHT - 64) style:UITableViewStylePlain];
//    self.tableView.backgroundColor = [UIColor lightGrayColor];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = 100;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    _tableView.scrollEnabled = NO;
    
    [_tableView registerClass:[DeleteDateCell class] forCellReuseIdentifier:NSStringFromClass([DeleteDateCell class])];
    
//    NSString *firstStr = [NSString stringWithFormat:@"%04ld-%02ld-01", [[CalendarTool shareCalendarTool] year:[NSDate date]],[[CalendarTool shareCalendarTool] month:[NSDate date]]];
//    NSString *lastStr = [NSString stringWithFormat:@"%04ld-%02ld-%02ld",[[CalendarTool shareCalendarTool] year:[NSDate date]], [[CalendarTool shareCalendarTool] month:[NSDate date]], [[CalendarTool shareCalendarTool] totaldaysInMonth:[NSDate date]]];
//    
    self.nameArr = @[@"起始日期", @"结束日期", @"账本", @"类型", @"分类"];
    _selectSource = @[@"请选择开始时间", @"请选择结束时间", @"全选", @"全选", @"全选"].mutableCopy;
    
    // 创建alertView以及添加方法
    self.alertView = [UIAlertController alertControllerWithTitle:nil message:@"日期信息不完善" preferredStyle:UIAlertControllerStyleAlert];

    
    UIAlertAction *certain = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

    }];
    
    [self.alertView addAction:certain];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _nameArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DeleteDateCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([DeleteDateCell class])];
    cell.nameLabel.text = _nameArr[indexPath.row];
    cell.currentStateLabel.text = _selectSource[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    switch (indexPath.row) {
        case 0:
        {
            _datePickerView.isBeginClick = YES;
            [_datePickerView show];
            

            
        }
            break;
        case 1:
        {
            _datePickerView.isBeginClick = NO;
            [_datePickerView show];
//            [_selectSource replaceObjectAtIndex:indexPath.row withObject:text];
//            [_tableView reloadData];
        }
            break;
        case 2:
        {
            MHActionSheet *actionSheet = [[MHActionSheet alloc] initSheetWithTitle:@"账本" style:MHSheetStyleWeiChat itemTitles:_accountBookArr];
            actionSheet.cancleTitle = @"取消";
            __weak typeof(self) weakSelf = self;
            [actionSheet didFinishSelectIndex:^(NSInteger index, NSString *title) {
                NSString *text = [NSString stringWithFormat:@"%@", title];
                [weakSelf.selectSource replaceObjectAtIndex:indexPath.row withObject:text];
                
                if ([text isEqualToString:@"没有账本数据"]) {
                    
                }else {
                    _model.accountName = text;
                }
                [weakSelf.tableView reloadData];
            }];
        }
            break;
        case 3:
        {
            MHActionSheet *actionSheet = [[MHActionSheet alloc] initSheetWithTitle:@"类型" style:MHSheetStyleWeiChat itemTitles:@[@"支出",@"收入"]];
            actionSheet.cancleTitle = @"取消";
            __weak typeof(self) weakSelf = self;
            [actionSheet didFinishSelectIndex:^(NSInteger index, NSString *title) {
                NSString *text = [NSString stringWithFormat:@"%@", title];
                [weakSelf.selectSource replaceObjectAtIndex:indexPath.row withObject:text];
                _model.type = text;
                [weakSelf.tableView reloadData];
            }];
        }
            break;
        case 4:
        {
            MHActionSheet *actionSheet = [[MHActionSheet alloc] initSheetWithTitle:@"分类" style:MHSheetStyleWeiChat itemTitles:_classArr];
            actionSheet.cancleTitle = @"取消";
            __weak typeof(self) weakSelf = self;
            [actionSheet didFinishSelectIndex:^(NSInteger index, NSString *title) {
                NSString *text = [NSString stringWithFormat:@"%@", title];
                [weakSelf.selectSource replaceObjectAtIndex:indexPath.row withObject:text];
                if ([text isEqualToString:@"没有分类数据"]) {
                    
                }else {
                _model.className = text;
                }
                [weakSelf.tableView reloadData];
            }];
        }
            break;
        default:
            break;
    }

}


- (void)backButtonAction:(UIButton *)button {
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}

- (void)datePickerBeginTime:(NSString *)beginTime {
    NSDate *date = [[CalendarTool shareCalendarTool] dateFromString:beginTime];
    _model.beginDate = [[CalendarTool shareCalendarTool] beginDateFromSmallStringDate:date];
    [_selectSource replaceObjectAtIndex:0 withObject:beginTime];
    [_tableView reloadData];
}

- (void)datePickerEndTime:(NSString *)endTime {
    NSDate *date = [[CalendarTool shareCalendarTool] dateFromString:endTime];
    _model.endDate = [[CalendarTool shareCalendarTool] endDateFromSmallStringDate:date];
    [_selectSource replaceObjectAtIndex:1 withObject:endTime];
    [_tableView reloadData];
}

- (void)finishButtonAction:(UIButton *)button {
//    NSLog(@"haah: %@, %@, %@, %@, %@", _model.beginDate, _model.endDate, _model.accountName, _model.type, _model.className);
    
    RLMRealm *realm = [RLMRealm defaultRealm];
    if (_model.beginDate != nil && _model.endDate != nil) {
        if (_model.accountName == nil) {
           // 没有设置账本名称
            
            if (_model.type == nil) {
                // 没有类型
                if (_model.className == nil) {
                    // 没有类名
                    // 000          // 账本_类型_类名
                    RLMResults *result = [DayBook allObjects];
                    
                    for (DayBook *dayBook in result) {
                       RLMResults *accountBooks = [dayBook.bookContent objectsWhere:@"time >  %@ and time < %@", _model.beginDate, _model.endDate];
                        [realm beginWriteTransaction];
                        [realm deleteObjects:accountBooks];
                        [realm commitWriteTransaction];
                    }
                }else {
                    // 有类名
                    //001
                    RLMResults *result = [DayBook allObjects];
                    
                    for (DayBook *dayBook in result) {
                        RLMResults *accountBooks = [dayBook.bookContent objectsWhere:@"time >  %@ and time < %@ and name = %@", _model.beginDate, _model.endDate, _model.className];
                        [realm beginWriteTransaction];
                        [realm deleteObjects:accountBooks];
                        [realm commitWriteTransaction];
                    }
                }
            }else {
                // 有类型
                if (_model.className == nil) {
                    // 没有类名
                    // 010
                    RLMResults *result = [DayBook allObjects];
                    
                    for (DayBook *dayBook in result) {
                        RLMResults *accountBooks = [dayBook.bookContent objectsWhere:@"time >  %@ and time < %@ and type = %@", _model.beginDate, _model.endDate, _model.type];
                        [realm beginWriteTransaction];
                        [realm deleteObjects:accountBooks];
                        [realm commitWriteTransaction];
                    }
                }else {
                   // 有类名
                    //011
                    RLMResults *result = [DayBook allObjects];
                    
                    for (DayBook *dayBook in result) {
                        RLMResults *accountBooks = [dayBook.bookContent objectsWhere:@"time >  %@ and time < %@ and name = %@ and type = %@", _model.beginDate, _model.endDate, _model.className, _model.type];
                        [realm beginWriteTransaction];
                        [realm deleteObjects:accountBooks];
                        [realm commitWriteTransaction];
                    }
                }
            }
            
        }else {
          // 设置了账本名称
            RLMResults *result = [DayBook objectsInRealm:realm where:@"accountBookName = %@", _model.accountName];
            DayBook *dayBook = [result firstObject];
            if (_model.type == nil) {
                if (_model.className == nil) {
                     // 100
                    RLMResults *accountBooks = [dayBook.bookContent objectsWhere:@"time >  %@ and time < %@", _model.beginDate, _model.endDate];
                    [realm beginWriteTransaction];
                    [realm deleteObjects:accountBooks];
                    [realm commitWriteTransaction];
                }else {
                     //101
                    RLMResults *accountBooks = [dayBook.bookContent objectsWhere:@"time >  %@ and time < %@ and name = %@", _model.beginDate, _model.endDate, _model.className];
                    [realm beginWriteTransaction];
                    [realm deleteObjects:accountBooks];
                    [realm commitWriteTransaction];
                }
            }else {
                if (_model.className == nil) {
                    //110
                    RLMResults *accountBooks = [dayBook.bookContent objectsWhere:@"time >  %@ and time < %@ and type = %@", _model.beginDate, _model.endDate, _model.type];
                    [realm beginWriteTransaction];
                    [realm deleteObjects:accountBooks];
                    [realm commitWriteTransaction];
                }else {
                    //111
                    RLMResults *accountBooks = [dayBook.bookContent objectsWhere:@"time >  %@ and time < %@ and name = %@ and type = %@", _model.beginDate, _model.endDate, _model.className, _model.type];
                    [realm beginWriteTransaction];
                    [realm deleteObjects:accountBooks];
                    [realm commitWriteTransaction];
                }
            }
        }
    }else if(_model.beginDate != nil || _model.endDate != nil) {
        [self presentViewController:_alertView animated:YES completion:^{
            
            
        }];
    }else {
        // 删除所有数据
        self.alert = [[UIAlertView alloc] initWithTitle:@"是否删除所有账本数据" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        _alert.alertViewStyle = UIAlertViewStyleDefault;
        [_alert show];
    }
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        RLMRealm *realm = [RLMRealm defaultRealm];
        RLMResults *result = [DayBook allObjects];
        [realm beginWriteTransaction];
        [realm deleteObjects:result];
        [realm commitWriteTransaction];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
